<template>
  <div class="header">
    <div class="homeIcon">
      <el-icon
          size="30px"
          @click="handleCollapse"
          :style="{transform:isCollapse ? '':'rotate(180deg)'}"
      >
        <Switch />
      </el-icon>
      <span>首页</span>
    </div>
    <div class="user"
         @mouseenter="isShowUserInfo('show')"
         @mouseleave="isShowUserInfo('leave')"
    >
      <img :src="userInfo.headImg">
      <div class="userInfo" v-show="show">
        <!--        <div>{{ userInfo.nick_name }}</div>-->
        <div>{{ userInfo.name }}</div>
        <div @click="onLogout">退出登录</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {defineProps,ref,onMounted,reactive} from 'vue';
import {getUserInfo} from '../api/index'
import router from "../router/index";

/**
 * 获取父组件的数据
 */
const {handleCollapse,isCollapse} =defineProps(['handleCollapse','isCollapse'])

/**
 * 鼠标移动个人信息的展示
 */
const show = ref(false);
const isShowUserInfo = (type) => {
  if (type === 'show') {
    show.value = true;
  } else {
    show.value = false;
  }
}

/**
 * 获取用户信息
 */
const  userInfo=reactive({
  name:'',
  headImg:''
})

// 获取用户信息接口
const getUserInfoData = async () => {
  const res = await getUserInfo();
  console.log('获取用户信息', res);
  if (res?.name && res?.head_img) {
    userInfo.name = res.name;
    userInfo.headImg = res.head_img;
    console.log('更新后的 userInfo:', userInfo); // 验证 userInfo 是否正确更新
  } else {
    console.warn('获取用户信息失败：缺少必要的字段');
  }
};


onMounted(() => {
  getUserInfoData()
})

/**
 * 退出登录按钮
 */
const onLogout = () => {
  console.log('正在退出登录...');
  router.push('/login');
  localStorage.removeItem('token');
  console.log('token 已移除:', localStorage.getItem('token'));
};


</script>

<style lang='less' scoped>
.userInfo {
  z-index: 22;
  display: flex;
  flex-direction: column;
  position: absolute;
  right: 0;
  bottom: -75px;
  background-color: #fff;
  border: 5px;
  box-shadow: 0 4px 8px 0 rgb(7 17 27 / 10%);
  text-align: center;

  div:hover {
    color: #409eff;
  }

  div {
    padding: 10px;
  }
}

.header {
  position: relative;
  height: 100%;
  align-items: center;
  display: flex;
  justify-content: space-between;

  .homeIcon {
    display: flex;
    align-items: center;

    span {
      margin-left: 10px;
    }
  }
  .placeholder {
    flex: 1; /* 添加占位元素 */
  }

  .user {
    display: flex;
    justify-content: center;
    width: 80px;

    img {
      width: 45px;
      height: 45px;
      border-radius: 50%;
    }
  }
}
</style>